package com.entertainment.ticketing.controller;

import com.entertainment.ticketing.dto.LoginRequest;
import com.entertainment.ticketing.dto.LoginResponse;
import com.entertainment.ticketing.entity.UserInfo;
import com.entertainment.ticketing.repository.UserInfoRepository;
import com.entertainment.ticketing.security.JwtTokenProvider;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.Optional;

@RestController
@RequestMapping("/api/auth/admin")
public class AdminAuthController {
    private final UserInfoRepository userRepo;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider tokenProvider;

    public AdminAuthController(UserInfoRepository userRepo, PasswordEncoder passwordEncoder, JwtTokenProvider tokenProvider) {
        this.userRepo = userRepo;
        this.passwordEncoder = passwordEncoder;
        this.tokenProvider = tokenProvider;
    }

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest req) {
        Optional<UserInfo> byUsername = userRepo.findByUsername(req.getUsernameOrEmail());
        Optional<UserInfo> byEmail = userRepo.findByEmail(req.getUsernameOrEmail());
        UserInfo user = byUsername.or(() -> byEmail)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户不存在"));
        if (user.getStatus() == 0) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "账户被禁用");
        }
        if (!"ADMIN".equalsIgnoreCase(user.getRole())) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "仅管理员可登录");
        }
        if (!passwordEncoder.matches(req.getPassword(), user.getPassword())) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "密码错误");
        }
        String token = tokenProvider.generateToken(user);
        LoginResponse resp = new LoginResponse(token, "Bearer", 3600L);
        return ResponseEntity.ok(resp);
    }

    @GetMapping("/info")
    public ResponseEntity<java.util.Map<String, Object>> info(Authentication auth) {
        if (auth == null) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "未登录");
        }
        String username = (String) auth.getPrincipal();
        UserInfo u = userRepo.findByUsername(username).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));
        if (!"ADMIN".equalsIgnoreCase(u.getRole())) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权限");
        }
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("id", u.getId());
        result.put("username", u.getUsername());
        result.put("email", u.getEmail());
        result.put("role", u.getRole());
        return ResponseEntity.ok(result);
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout() {
        // JWT 无状态，前端删除令牌即可
        return ResponseEntity.ok().build();
    }
}